#include "../Codec/ICodec.h"
#include "TextAdder.h"
#include "../Timestamp.h"
#include "../Codec/Codec.h"
#include "../currentThread.h"

#include <fstream>
#include <unistd.h>
#include <sys/syscall.h>
#include <muduo/base/Logging.h>

void TextAdder::setInitialContent(const std::string &initialContent) {
    ICodec_->setInitialContent(initialContent);
}

TextAdder::TextAdder()
     : ICodec_(new Codec) 
       {}

std::string TextAdder::addMark() {
    std::string fileName = "image/text/img" + Timestamp::now().toString() +
            currentThread::getTidAsString() + ".png";
    std::string retName = "image/text/ret" + Timestamp::now().toString() +
            currentThread::getTidAsString() + ".png";
    ICodec_->decode();
    saveFile(fileName, ICodec_->getResultContentDecodeContent1());

    std::string text =ICodec_->getResultContentDecodeContent2();
    cv::Mat image = cv::imread(fileName);

    if (image.empty()) {
        fprintf(stderr, "Adder::addMarkByText(): image is empty!\n");
        return "";
    }
    if (text.empty()) {
        fprintf(stderr, "Adder::addMarkByText(): context is empty!\n");
        return "";
    }

    cv::Point p = cv::Point(image.rows - text.size() * 9, image.cols - 8);
    cv::putText(image, text, p, cv::FONT_HERSHEY_PLAIN, 1.0, cv::Scalar(0, 0, 0), 1);
    saveFile(retName, image);

    deleteFile(fileName);
    
    return retName;
}

void TextAdder::saveFile(const std::string &fileName, const std::string &fileContent) {
    std::ofstream file(fileName);
    file << fileContent;
    file.close();
}

void TextAdder::saveFile(const std::string &fileName, cv::Mat fileContent) {
    cv::imwrite(fileName, fileContent);
}

void TextAdder::deleteFile(const std::string &fileName)
{
    int isOK = ::unlink(fileName.c_str());
    if (isOK < 0)
        LOG_INFO << "PictureAdder::deleteFile(): remove file failed";
}